package medicaldeptsubDao

import (
	"gorm.io/gorm/clause"
	"jjqzplucky.site/sz-core/internal/models"
	medicalDeptSubModel "jjqzplucky.site/sz-core/internal/models/medical_dept_sub"
	"jjqzplucky.site/sz-core/pkg/utils"
)

func SelectAll() []medicalDeptSubModel.MedicalDeptSub {
	db := models.DB
	var list []medicalDeptSubModel.MedicalDeptSub
	db.Model(&medicalDeptSubModel.MedicalDeptSub{}).Find(&list)
	return list
}

func GetById(id uint64) medicalDeptSubModel.MedicalDeptSub {
	db := models.DB
	model := medicalDeptSubModel.MedicalDeptSub{ }
	model.Id = id
	db.Find(&model)
	return model
}

func GetListByMedicalId(id uint64, param medicalDeptSubModel.QueryParam) utils.PageResult {
	db := models.DB
	var count int64
	var list []medicalDeptSubModel.MedicalDeptSub
	query := db.Model(&medicalDeptSubModel.MedicalDeptSub{}).Where("dept_id = ?", id)
	if param.Name != nil {
		query = query.Clauses(clause.Like{Column: "name", Value: "%" + *param.Name + "%"})
	}
	if param.Location != nil {
		query = query.Clauses(clause.Like{Column: "name", Value: "%" + *param.Location + "%"})
	}
	if param.Page != 0 {
		query = query.Offset((param.Page - 1) * param.PageSize)
	} else {
		query = query.Offset(0)
	}
	if param.PageSize != 0 {
		query = query.Limit(param.PageSize)
	} else {
		query = query.Limit(10)
	}
	query.Count(&count).Find(&list)

	return utils.PageResult{
		List: list,
		Page: param.Page,
		PageSize: param.PageSize,
		Total: count,
	}
}

func Create(model medicalDeptSubModel.MedicalDeptSub) error { 
	db := models.DB
	return db.Create(model).Error
}

func Update(model medicalDeptSubModel.MedicalDeptSub) error {
	db := models.DB
	return db.Omit("create_time").Save(model).Error
}

func Delete(id uint64) error {
	db := models.DB
	return db.Delete(medicalDeptSubModel.MedicalDeptSub{}, id).Error
}